// pages/chatPage/chatpage.js

import {API, rootPath, wsPath} from '../../utils/const'
import webSocketManager from '../../utils/webSocketManager'
  /**
   * Page initial data
   */
// chat.js
Page({
    data: {
      messages: [],
      chatTarget: {
          id: -1,
          name: 'test',
          role: 'testRole1'
      },
      chatOwnerId: -1,
      chatOwnerRole: 'testRole2',
      inputMessage: '',
      isSending: false,
    },
  
    onInput(e) {
        this.setData({
          inputMessage: e.detail.value,
        });
      },
    // Function to send a new message
    sendMessage(e) {
        if (this.data.isSending) {
            return; // Prevent sending if a message is already being sent
        }

        this.setData({
            isSending: true // Disable the button
        });
      if(this.data.inputMessage === ''){
          return;
      }
      const newChatMessage = {
          fromRole: this.data.chatOwnerRole,
          fromId: this.data.chatOwnerId,
          toRole: this.data.chatTarget.role,
          toId: this.data.chatTarget.id,
          content: this.data.inputMessage,
      }
      console.log(newChatMessage);
      webSocketManager.sendMessage({
        messageType: "ChatMessage",
        message: newChatMessage,
      })    
      this.setData({
        inputMessage : '',
        isSending: false
      });
    },
  
  /**
   * Lifecycle function--Called when page load
   */
  onLoad(options) {
    const that = this;
    const { id, name, role } = options;
    const socketUrl = wsPath + API.backendWs;
    const getChatHistoryUrl = rootPath + API.getChatHistory;
    let header = {};
    let token = wx.getStorageSync('token');
    let userId = Number(wx.getStorageSync('LoginId'));
    let userRole = wx.getStorageSync('loginType');
    let messageList = [];
    header['authorization'] = "Bearer " + token;
    const chatTarget = {
        id : Number(id),
        name: name,
        role: role
    }
    
    console.log(`Calling ${getChatHistoryUrl}  with ${userRole} - ${userId} ... `);
    wx.request({
      url: getChatHistoryUrl,
      header: header,
      data: {
          id1: Number(userId),
          role1: userRole,
          id2: id,
          role2: role
        },
      method: 'GET',
      timeout: 2000,
      success(res) {
        if (res.statusCode === 200) {
          console.log(res.data);
          let response = res.data;
          messageList = that.handleChatMessages(response)
          that.setData({
              messages: messageList,
          })
          setTimeout(() => {
            that.setData({bottomViewId: `item${that.data.messages.length-1}`,
          })})     
        } else {
          console.error('Failed to fetch data from {}', url);
        }
      },
      fail(err) {
        console.error('Request failed', err);
      }})
    webSocketManager.connect(socketUrl);
    webSocketManager.registerCallback('ChatMessage', this.handleWsChatMessage);
    that.setData({
      chatTarget: chatTarget,
      chatOwnerId: userId,
      chatOwnerRole: userRole
    });
    
  },

  handleWsChatMessage: function(data){
    const that = this;
    // console.log(`Get ws chat message ${JSON.stringify(data)}, start process..`); 
    const newMessage = that.handleChatMessage(data)
    that.setData({
        messages: [...that.data.messages, newMessage],
    })
    setTimeout(() => {
        that.setData({bottomViewId: `item${that.data.messages.length-1}`,
      })})
  },
  handleChatMessage: function(chatMessage) {
    const that = this
    if (chatMessage.toRole.toUpperCase() === that.data.chatOwnerRole.toUpperCase()
        && chatMessage.toId === that.data.chatOwnerId
        && chatMessage.fromRole.toUpperCase() === that.data.chatTarget.role.toUpperCase()
        && chatMessage.fromId === that.data.chatTarget.id)
        {
            return {
                content: chatMessage.content,
                isSender: true
              }
        }          
      else if(chatMessage.toRole.toUpperCase() === that.data.chatTarget.role.toUpperCase()
        && chatMessage.toId === that.data.chatTarget.id
        && chatMessage.fromRole.toUpperCase() === that.data.chatOwnerRole.toUpperCase()
        && chatMessage.fromId === that.data.chatOwnerId){
            return {
                content: chatMessage.content,
                isSender: false
            }
        }
  },
  handleChatMessages: function(chatMessages) {
      const that = this;
      let messageList = []
      const sortedData = [...chatMessages].sort((a, b) => Number(a.createTimeEpoch) - Number(b.createTimeEpoch));
      sortedData.forEach(element => {
        messageList.push(that.handleChatMessage(element))});
      console.log(messageList);
      return messageList;
  },

  /**
   * Lifecycle function--Called when page is initially rendered
   */
  onReady() {

  },

  /**
   * Lifecycle function--Called when page show
   */
  onShow() {
  },

  /**
   * Lifecycle function--Called when page hide
   */
  onHide() {

  },

  /**
   * Lifecycle function--Called when page unload
   */
  onUnload() {
    webSocketManager.unregisterCallback('ChatMessage', this.handleWsChatMessage);
  },

  /**
   * Page event handler function--Called when user drop down
   */
  onPullDownRefresh() {

  },

  /**
   * Called when page reach bottom
   */
  onReachBottom() {
  },

  /**
   * Called when user click on the top right corner to share
   */
  onShareAppMessage() {

  }
})